package com.android.systemui.qs.tiles;

import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.StatusBarManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.provider.Settings;
import android.provider.Settings.Global;
import android.service.quicksettings.Tile;
import android.telephony.CarrierConfigManager;
import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.UniSettings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.view.WindowManagerGlobal;
import android.widget.CheckBox;
import android.widget.Switch;
import android.widget.Toast;

import com.android.ims.ImsManager;
import com.android.ims.internal.ImsManagerEx;
import com.android.internal.logging.MetricsLogger;
import com.android.internal.telephony.TelephonyIntents;
import com.android.systemui.plugins.qs.QSTile.BooleanState;
import com.android.systemui.qs.QSHost;
import com.android.systemui.qs.tileimpl.QSTileImpl;
import com.android.systemui.R;

/** Quick settings tile: Vowifi **/
public class VoWifiTile extends QSTileImpl<BooleanState> {
    static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
    static final String WIFI_CALLING_SETTING_ACTIVITY_NAME =
            "com.android.settings.Settings$WifiCallingSettingsActivity";
    static final Intent WIFICALLING_SETTINGS = new Intent().setComponent(new ComponentName(
            SETTINGS_PACKAGE_NAME, WIFI_CALLING_SETTING_ACTIVITY_NAME));
    static final boolean DBG = true;
    static final String TAG = "QSVoWifiTile";
    private TelephonyManager mTelephonyManager;
    private boolean mListening;
    private boolean mVoWifiAvailable;
    public static final int QS_VOWIFI_SERVICE = 951;
    /*UNISOC: add for bug691804 carrier special new feature*/
    private AlertDialog mVowifiEnableDialog = null;
    private static final String ENHANCED_VOWIFI_TOAST_SHOW_ENABLED =
            UniSettings.UniGlobal.ENHANCED_VOWIFI_TOAST_SHOW_ENABLED;
    /* @} */
    private CarrierConfigManager mConfigManager;
    private PersistableBundle mCarrierConfig;
    private String mSyncVolte;
    private CharSequence[] mVariantTitles;
    private int mDefaultDataSubId = 0;
    private int mPhoneId = 0;
    private ImsManager mImsManager;
    private static final int VARIANT_TITLE_VOLTE = 0;
    private static final int VARIANT_TITLE_ADVANCED_CALL = 1;
    private static final int VARIANT_TITLE_4G_CALLING = 2;

    private final ContentObserver mObserver;

    public VoWifiTile(QSHost host) {
        super(host);
        Log.d(TAG, "create VoWifiTile");
        mTelephonyManager = TelephonyManager.from(mContext);
        mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
        mDefaultDataSubId = SubscriptionManager.getDefaultDataSubscriptionId();
        mPhoneId = SubscriptionManager.getPhoneId(mDefaultDataSubId);
        mImsManager = ImsManager.getInstance(mContext, mPhoneId);
        mObserver = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                Log.d(TAG, "onChange");
                refreshState();
            }
        };
        mConfigManager = (CarrierConfigManager) mContext.getSystemService(Context.CARRIER_CONFIG_SERVICE);
        mVariantTitles = mContext.getResources()
                .getTextArray(R.array.enhanced_4g_lte_mode_title_variant);
    }

    /* UNISOC: Modify for bug1335095 @{ */
    public void unregisterListen() {
        if (mTelephonyManager != null) {
            mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
        }
    }
    /* @} */

    @Override
    public BooleanState newTileState() {
        return new BooleanState();
    }

    @Override
    public void handleSetListening(boolean listening) {
        super.handleSetListening(listening);
        if (mListening == listening) {
            return;
        }
        mListening = listening;
        //UNISOC: add for bug691804 carrier special new feature
        if (listening) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
            intentFilter.addAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
            mContext.registerReceiver(mBroadcastReceiver, intentFilter);
            mDefaultDataSubId = SubscriptionManager.getDefaultDataSubscriptionId();
            mPhoneId = SubscriptionManager.getPhoneId(mDefaultDataSubId);
            mImsManager = ImsManager.getInstance(mContext, mPhoneId);
            mContext.getContentResolver().registerContentObserver(getNotifyContentUri(
                SubscriptionManager.WFC_ENABLED_CONTENT_URI, true, mDefaultDataSubId),
                true, mObserver);
        } else {
            mContext.unregisterReceiver(mBroadcastReceiver);
            mContext.getContentResolver().unregisterContentObserver(mObserver);
        }
    }

    PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            if(state != TelephonyManager.CALL_STATE_OFFHOOK){
                refreshState();
            }
        };
    };

    private static Uri getNotifyContentUri(Uri uri, boolean usingSubId, int subId) {
        return (usingSubId) ? Uri.withAppendedPath(uri, "" + subId) : uri;
    }

    @Override
    public Intent getLongClickIntent() {
        if (mImsManager.isWfcEnabledByPlatform()) {
            return WIFICALLING_SETTINGS;
        } else {
            return new Intent();
        }
    }

    @Override
    protected void handleClick() {
        MetricsLogger.action(mContext, getMetricsCategory(), !mState.value);

        if (getState().state == Tile.STATE_UNAVAILABLE) {
            return;
        }
        /*UNISOC: add for bug691804 carrier special new feature @{ */
        boolean showVowifiEnableDiaglog = mContext.getResources()
                .getBoolean(R.bool.config_show_vowifi_enable_dialog);
        if (showVowifiEnableDiaglog) {
            setVoWifiEnabledForCarrier();
        /* @} */
        } else {
            setVolteEnableWithNotice();
            setVoWifiEnabled();
        }
    }

    /*UNISOC: add for bug691804 carrier special new feature*/
    public AlertDialog showVowifiEnableDialog(final Context context) {

        int enabled = Settings.Global.getInt(context.getContentResolver(),
                ENHANCED_VOWIFI_TOAST_SHOW_ENABLED, 0);
        boolean nomore = (enabled == 1);
        if (nomore) {
            Log.d(TAG, "showVoWifiNotification nomore ");
            return null;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.xml.vowifi_register_dialog, null);

        builder.setView(view);
        builder.setTitle(context.getString(R.string.vowifi_connected_title));
        builder.setMessage(context.getString(R.string.vowifi_connected_message));
        final CheckBox cb = (CheckBox) view.findViewById(R.id.nomore);

        builder.setPositiveButton(context.getString(R.string.vowifi_connected_continue),
                new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (cb.isChecked()) {
                    Settings.Global.putInt(context.getContentResolver(),
                            ENHANCED_VOWIFI_TOAST_SHOW_ENABLED, 1);
                }
                Log.d(TAG, "Vowifi service Continue, cb.isChecked = " + cb.isChecked());
                setVolteEnableWithNotice();
                mImsManager.setWfcSetting(true);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        builder.setNegativeButton(context.getString(R.string.vowifi_connected_disable),
                new android.content.DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (cb.isChecked()) {
                    Settings.Global.putInt(context.getContentResolver(),
                            ENHANCED_VOWIFI_TOAST_SHOW_ENABLED, 1);
                }
                Log.d(TAG, "Vowifi service disable, cb.isChecked = " + cb.isChecked());
                mImsManager.setWfcSetting(false);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        builder.setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog = builder.create();
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
        dialog.show();
        return  dialog;
    }
    /* @} */

    private void setVoWifiEnabled() {
        Log.d(TAG, "setVoWifiEnabled: " + !mState.value);
        mImsManager.setWfcSetting(!mState.value);
    }

    /*UNISOC: add for bug691804 carrier special new feature*/
    private void setVoWifiEnabledForCarrier() {
        if (DBG) {
          Log.d(TAG, "setVoWifiEnabledForCarrier: " + !mState.value);
        }
        if (!mState.value) {
            if (mVowifiEnableDialog != null) {
                mHost.collapsePanels();
                dissmissDefaultKeyguard();
                return;
            }
            mVowifiEnableDialog = showVowifiEnableDialog(mContext);
            if (mVowifiEnableDialog != null) {
                mVowifiEnableDialog.setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        // TODO Auto-generated method stub
                        mVowifiEnableDialog = null;
                    }
                });
            }

            if (mVowifiEnableDialog == null) {
                setVolteEnableWithNotice();
                setVoWifiEnabled();
            } else {
                StatusBarManager statusBarManager = (StatusBarManager) mContext
                        .getSystemService(android.app.Service.STATUS_BAR_SERVICE);
                statusBarManager.collapsePanels();
                dissmissDefaultKeyguard();
            }
        } else {
            setVoWifiEnabled();
        }
    }

    private void dissmissDefaultKeyguard() {
        KeyguardManager keyguardManager =
                (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
        Log.d(TAG, "keyguardManager.isKeyguardLocked() = " + keyguardManager.isKeyguardLocked());
        if (keyguardManager.isKeyguardLocked()) {
            try {
                WindowManagerGlobal.getWindowManagerService().dismissKeyguard(null ,null);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /* @} */
    @Override
    public CharSequence getTileLabel() {
        return mContext.getString(R.string.quick_settings_vowifi_label);
    }

    @Override
    protected void handleUpdateState(BooleanState state, Object arg) {
        boolean available = mImsManager.isWfcEnabledByPlatform();
        state.value = mImsManager.isWfcEnabledByUser();
        state.label = removeDoubleQuotes(getSSID());
        Log.d(TAG, "handleUpdateState: available = " + available + " state.value = " + state.value);
        int phoneId = SubscriptionManager.getPhoneId(SubscriptionManager.getDefaultDataSubscriptionId());
        if (SubscriptionManager.isValidPhoneId(phoneId) && available && (!isInCall())) {
            if (state.value) {
                state.state = Tile.STATE_ACTIVE;
                state.icon = ResourceIcon.get(R.drawable.ic_qs_vowifi_ex);
                state.label = removeDoubleQuotes(getSSID());
                state.contentDescription =  mContext.getString(
                        R.string.accessibility_quick_settings_vowifi_on);
            } else {
                state.state = Tile.STATE_INACTIVE;
                state.icon = ResourceIcon.get(R.drawable.ic_qs_vowifi_ex);
                state.label = mContext.getString(R.string.quick_settings_vowifi_label);
                state.contentDescription =  mContext.getString(
                        R.string.accessibility_quick_settings_vowifi_off);
            }
        } else {
            state.state = Tile.STATE_UNAVAILABLE;
            state.icon = ResourceIcon.get(R.drawable.ic_qs_vowifi_ex);
            state.label = mContext.getString(R.string.quick_settings_vowifi_label);
            return;
        }
        state.expandedAccessibilityClassName = Switch.class.getName();
    }

    private String getSSID() {
        WifiManager wifi = (WifiManager) mContext.getSystemService(
                Context.WIFI_SERVICE);
        if (wifi != null) {
            WifiInfo info = wifi.getConnectionInfo();
            if (info != null) {
                return (info.getSSID() != WifiManager.UNKNOWN_SSID) ?
                        info.getSSID() : mContext.getString(R.string.quick_settings_vowifi_label);
            }
        }
        return mContext.getString(R.string.quick_settings_vowifi_label);
    }

    private static String removeDoubleQuotes(String string) {
        if (string == null) {
            return null;
        }
        final int length = string.length();
        if ((length > 1) && (string.charAt(0) == '"') && (string.charAt(length - 1) == '"')) {
            return string.substring(1, length - 1);
        }
        return string;
    }

    @Override
    public int getMetricsCategory() {
        return QS_VOWIFI_SERVICE;
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED)){
                refreshState();
            } else if (action.equals(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)) {
                mSyncVolte = String.format(mContext.getString(R.string.vowifi_service_volte_open_auto_synchronously), getVolteTitle());
            }
        }
    };

    private void setVolteEnableWithNotice() {
        /* UNISOC: when user open vowifi,then volte will be open synchronously for bug770787. @{ */
        /* UNISOC: bug 811336 && 977043@{ */
        if(!ImsManagerEx.synSettingForWFCandVoLTE(mContext)) {
            return;
        }
        boolean isVolteEnabled = mImsManager.isEnhanced4gLteModeSettingEnabledByUser();
        Log.d(TAG, "isVolteEnabled = " + isVolteEnabled);
        if (mImsManager.isVolteEnabledByPlatform() && !mState.value
                && !isVolteEnabled) {
            mImsManager.setEnhanced4gLteModeSetting(true);
            /* @} */
            showToast(mContext, mSyncVolte, Toast.LENGTH_LONG);
        }
        /* @} */
    }

    private String getVolteTitle(){
        if (mConfigManager != null) {
            mCarrierConfig = mConfigManager.getConfigForSubId(SubscriptionManager.getDefaultDataSubscriptionId());
            if (mCarrierConfig != null) {
                boolean show4GForLTE = mCarrierConfig.getBoolean(
                    CarrierConfigManager.KEY_SHOW_4G_FOR_LTE_DATA_ICON_BOOL);
                int variant4glteTitleIndex = mCarrierConfig.getInt(
                    CarrierConfigManager.KEY_ENHANCED_4G_LTE_TITLE_VARIANT_INT);
                if (variant4glteTitleIndex != VARIANT_TITLE_ADVANCED_CALL) {
                    variant4glteTitleIndex = show4GForLTE ? VARIANT_TITLE_4G_CALLING : VARIANT_TITLE_VOLTE;
                }
                return mVariantTitles[variant4glteTitleIndex].toString();
            }
        }
        return null;
    }

    private static void showToast(Context context, String text, int duration) {
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

    private boolean isInCall() {
        return mTelephonyManager.getCallState(mDefaultDataSubId) != TelephonyManager.CALL_STATE_IDLE;
    }
}
